import { Text, TextStyle } from '@pixi/text'
import FontFaceObserver from 'fontfaceobserver'
import { Application } from '@pixi/app';
import { Container } from '@pixi/display';
import { createButton } from './button';
import { Ticker } from '@pixi/core';
import './font.css'

const style = new TextStyle({
    fill: [
        "#FF844E",
        "#FFC592"
    ],
    fillGradientStops: [
        0,
        100
    ],
    fontFamily: "FZShengShiKaiShuS-EB-GB",
    fontSize: 54,
    fontWeight: '400',
    fontStyle: 'italic',
    padding: 10,
    stroke: "#1f6476",
    strokeThickness: 6,
    lineJoin: 'round',
});

let loaded = false;
async function loadFont() {
    if (loaded) {
        return;
    }

    // 加载字体
    const fontface = new FontFaceObserver("FZShengShiKaiShuS-EB-GB")
    await fontface.load("123")
    loaded = true;
}

let runingTextList: Text[] = [];

function runingTicker(c: Container) {
    let t = new Ticker()
    t.maxFPS = 60;
    t.autoStart = true;
    t.speed = 1;

    t.add(() => {
        runingTextList.filter(tx => tx.alpha <= 0).forEach(tx => {
            tx.destroy();
            c.removeChild(tx);
        });

        const activeList = runingTextList.filter(tx => tx.alpha > 0);
        runingTextList = activeList;

        activeList.forEach(tx => {
            tx.alpha -= 0.02;
            tx.y -= 1;

            let x = tx.scale.x;
            tx.scale.set(x - 0.01, x - 0.01);
        })
    });

    return t;
}

export async function addKillText(app: Application, duration = 10) {
    await loadFont()

    const c = new Container();
    c.x = 20;
    c.y = 200;

    const pushText = () => {
        let value = (Math.random() * 1000).toFixed(0);
        if ((Math.random() * 10) > 5) {
            value = "+" + value
        } else {
            value = "-" + value
        }

        let t = new Text(value, style);
        t.scale.set(0.5);

        let x = Math.random() * 300;
        let y = Math.random() * 200;
        t.y = y;
        t.x = x;

        runingTextList.push(t);
        c.addChild(t);
    }
    setInterval(pushText, duration);

    {
        let button = createButton("攻击", pushText);
        button.x = 200;
        button.y = 500;

        app.stage.addChild(button);
    }
    app.stage.addChild(c);

    runingTicker(c);
}